package dao;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
 *
 * @author Eri Setiawan
 */
public class ResourceManager{
    private static Document document;
    private static Driver driver = null;

   // private BasicDataSource dataSource;

    public static synchronized Connection getConnection() throws SQLException {
        if (driver == null) {
            try {
                document  = parseXML(new BufferedReader(new FileReader("conf/context.xml")));
                Class jdbcDriverClass = Class.forName(getAttribute(document, "@driverClassName"));
                driver = (Driver) jdbcDriverClass.newInstance();
                DriverManager.registerDriver( driver );
            }
            catch (Exception e) {
                System.out.println( "Failed to initialise JDBC driver" );
                e.printStackTrace();
            }
        }
        String url;
        String username;
        String password;
        try {
            url = getAttribute(document, "@url");
            username = getAttribute(document, "@username");
            password = getAttribute(document, "@password");
            return DriverManager.getConnection( url, username, password);
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            return null;
        }
    }
    public static void close(Connection conn) {
        try {
            if (conn != null) conn.close();
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    public static void close(PreparedStatement stmt) {
        try {
            if (stmt != null) stmt.close();
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) rs.close();
        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
        }
    }
    private static Document parseXML(BufferedReader reader) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(new InputSource(reader));
    }

    private static String getAttribute(Document document, String attribute) throws XPathExpressionException {
        return (String) XPathFactory.newInstance().newXPath().compile("/Context/Resource/" + attribute)
                .evaluate(document.getDocumentElement(), XPathConstants.STRING);
    }
}

